#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime, \
    Boolean, TIMESTAMP, func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""user_base collection has 
   name:    头像地址hash key (int)
   used:    是否使用过(boolean)
   ctime:   创建时间（datetime）
"""


class CrawlUserNameItem(object):

    def to_dict(self):
        res = {}
        res['name'] = self.name
        res['used'] = self.used
        # res['ctime'] = self.ctime
        return res

    def __repr__(self):
        return "%d" % (self.name)


crawl_user_name_table = Table(
    'crawl_user_name', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', Unicode(64), index=True, unique=True, nullable=False),
    Column('used', Boolean, default=False),
    Column('ctime', TIMESTAMP, server_default=func.now())
)

mapper(CrawlUserNameItem, crawl_user_name_table)


def create_crawl_user_name_table_if_not_exist():
    metadata.create_all(engine)


def add_crawl_user_name_item(p_item):
    item = CrawlUserNameItem()
    item.name = p_item['name']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_crawl_user_name_all(p_begin, p_limit):
    try:
        session = Session()
        items = session.query(CrawlUserNameItem).offset(p_begin).limit(p_limit).all()
        if not items:
            return None
        return [item['userid'] for item in items.to_dict()]
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


if __name__ == "__main__":
    create_crawl_user_name_table_if_not_exist()
